package com.mccken.springframework.core.io;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import cn.hutool.core.lang.Assert;

/**
 * @program: mccken-collect
 * @description:
 * @author: mccken
 * @create: 2022-11-30 15:49
 **/
public class UrlResource implements Resource {
	
	private final URL url;
	
	public UrlResource(URL url) {
		Assert.notNull(url, "URL must not be null");
		this.url = url;
	} 
	
	@Override
	public InputStream getInputStream() throws IOException {
		URLConnection con = this.url.openConnection();
		try {
			return con.getInputStream();
		}
		catch (IOException e) {
			if (con instanceof HttpURLConnection) {
				((HttpURLConnection)con).disconnect();	
			}
			throw e;
		}
		
	}
}
